
import axios, {
    Method,
    InternalAxiosRequestConfig,
    AxiosResponse,
    AxiosProgressEvent
  } from 'axios';


  interface ConfigType {
    headers?: { [key: string]: string };
    timeout?: number;
    onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
    cancelToken?: AbortController;
    maxQuantity?: number;
    withCredentials?: boolean;
  }

  interface ResponseDataType {
    code: number;
    message: string;
    data: any;
  }

const instance = axios.create({
    timeout: 60000, // 超时时间
    headers: {
      'content-type': 'application/json'
    }
});

  
function request(
    url:string,
    data:any,
    {...config},
    method: Method
): any {
    return instance.request({
        baseURL:'/api',
        url,
        method,
        data:data,
        ...config,
    }).then((res)=>{
        return checkRes(res.data)
    })
    .catch((err) => responseError(err))
}

export function GET<T = undefined>(url: string, params = {}, config: ConfigType = {}): Promise<T> {
    return request(url, params, config, 'GET');
}

/**
 * 响应数据检查
 */
function checkRes(data: ResponseDataType) {
    if (data === undefined) {
      console.log('error->', data, 'data is empty');
      return Promise.reject('服务器异常');
    } else if (data.code < 200 || data.code >= 400) {
      return Promise.reject(data);
    }
    return data.data;
  }

function responseError(err: any) {
    console.log('error->', '请求错误', err);

    if (typeof err === 'string') {
        return Promise.reject({ message: err });
      } 

      if (err?.message) {
        return Promise.reject('message');
      }

      if (err?.response?.data) {
        return Promise.reject(err?.response?.data);
      }
      return Promise.reject(err);
}